<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="text" name="search">
<div id="display_content"></div>
<script src="template.js"></script>
<script id="my-tpl" type="text/html">
    <table border="1" width="100%">
        <tr><th>id</th><th>username</th><th>action</th><th>操作</th></tr>
        <% for(var i = 0; i<data.length; i++){ %>
        <tr>
            <td><%=data[i].id%></td>
            <td><%=data[i].username%></td>
            <td><%=data[i].action%></td>
            <td><a href="">删除</a></td>
        </tr>
        <% }%>
    </table>
</script>
<script>
    var search = document.getElementsByName('search')[0];
    var tpl = document.getElementById('my-tpl');
    var display_content = document.getElementById('display_content');
    search.onkeyup = function (e)
    {
        if (e.keyCode == 13) { // 判断是否敲上回车
            var xhr = new XMLHttpRequest();
            xhr.open('post' , '4-php.php');
            // 如果请求方式是post， 那么在发送请求前，需要额外添加一个头部协议
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send('search='+this.value);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4)
                {
                    if(xhr.status == 200)
                    {
                        // 以文本的方式输出请求内容
                        var res = JSON.parse(xhr.responseText);
                        var html = template(tpl.innerHTML , {'data':res});
                        display_content.innerHTML = html;
                    }
                }
            }
        }
    }

</script>
</body>
</html>